package com.algorithm.base.backtracking;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 复原ip地址
 *
 * @author Amadeus
 * @date 2023/11/08
 */
public class RestoreIpAddresses {
    List<String> result = new ArrayList<>();
    Deque<String> deque = new LinkedList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s.length() > 12) {
            return result;
        }
        backTracking(0, s);
        return result;
    }

    public void backTracking(int index, String s) {
        if (deque.size() == 4) {
            if (index == s.length()) {
                result.add(String.join(".", deque));
            }
            return;
        }
        for (int i = index; i < s.length(); i++) {
            String part = s.substring(index, i + 1);
            if (isValidPart(part)) {
                deque.addLast(part);
                backTracking(i + 1, s);
                deque.removeLast();
            } else {
                break;
            }
        }
    }

    public boolean isValidPart(String part) {
        if (part.length() > 1 && part.charAt(0) == '0') {
            return false;
        }
        int num = Integer.parseInt(part);
        return num >= 0 && num <= 255;
    }

}
